import fs = require('fs')
import path = require('path')
import ffmpeg = require('fluent-ffmpeg')

export function rmNotMedia(filePath: string){
    const suffix = ['.mp4', '.mkv', '.avi', '.wmv', '.rmvb', '.ts','.jpg','.png','.jpeg']
    const files = recursiveFileBySuffix(filePath,suffix,true)
    files.forEach((file)=>{
        console.log(`delete file ${file} , it is not media.`)
        fs.unlinkSync(file)
    })
}

export function rmEmptyDirRecursive(dirPath: string) {
    const allFiles = fs.readdirSync(path.resolve(dirPath), {
        withFileTypes: true
    })
    allFiles.forEach((file) => {
        if (file.isDirectory()) {
            const children = fs.readdirSync(path.resolve(dirPath, file.name))
            if(children.length === 0){
                fs.rmdirSync(path.resolve(dirPath,file.name))
                console.log(`delete empty dir ${path.resolve(dirPath,file.name)}`)
                rmEmptyDir(dirPath)
            }else{
                rmEmptyDirRecursive(path.resolve(dirPath, file.name))
            }
        }
    })
}

function rmEmptyDir(dirPath: string){
    const children = fs.readdirSync(path.resolve(dirPath))
    if(children.length === 0){
        fs.rmdirSync(path.resolve(dirPath))
        console.log(`delete empty dir ${path.resolve(dirPath)}`)
    }
}


/**
 * 删除短视频
 * @param {string} filePath 目录
 * @param {number} maxDuration 最大时长，秒
 */
export async function rmSmallVideo(filePath: string,maxDuration: number){
    const suffix = ['.mp4', '.mkv', '.avi', '.wmv', '.rmvb', '.ts']
    const videos = recursiveFileBySuffix(filePath,suffix)
    const res: Map<string,any> = await videoDuration(videos)
    res.forEach((value,key)=>{
        if(value < maxDuration){
            console.log(`delete video ${key} duration[${value}s]`)
            fs.unlinkSync(key)
        }
    })
}

function videoDuration(videos:string[],durationMap:Map<string,any> = new Map<string,any>()): Promise<Map<string,any>>{
    return new Promise((resolve)=>{
        if(videos.length !== 0){
            const pathUrl = videos.shift()
            if(pathUrl){
                ffmpeg.ffprobe(pathUrl, (err: any, data: { format: { duration: any } }) => {
                    durationMap.set(pathUrl,data.format.duration)
                    resolve(videoDuration(videos,durationMap))
                })
            }
        }else{
            resolve(durationMap)
        }
    })
}

/**
 * 以后缀递归文件
 * @param {string} dirPath 目标目录
 * @param {array} suffixs 后缀列表
 * @param {boolean} exclude true:排除掉后缀列表中的文件，返回剩下的；false:留下后缀列表中的文件，过滤其他的。
 * @returns
 */
export function recursiveFileBySuffix(dirPath: string,suffixs: string[],exclude: boolean = false) {
    let files = []
    const allFiles = fs.readdirSync(path.resolve(dirPath), {
        withFileTypes: true
    })
    allFiles.forEach((file) => {
        if (file.isFile()) {
            if(exclude && !suffixs.includes(path.extname(file.name).toLocaleLowerCase())){
                files.push(path.resolve(dirPath, file.name))
            }else if(!exclude && suffixs.includes(path.extname(file.name).toLocaleLowerCase())) {
                files.push(path.resolve(dirPath, file.name))
            }
        } else {
            files = files.concat(recursiveFileBySuffix(path.resolve(dirPath, file.name),suffixs,exclude))
        }
    })
    return files
}